package cn.itcast.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.dataflow.DataflowJob;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class MyDataFlowJob implements DataflowJob<Integer> {
    //模拟10000个数据
    private static List<Integer> dataOdd; //奇数
    private static List<Integer> dataEvent; //偶数
    
    static {
        dataOdd = new ArrayList<>();
        dataEvent = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            if (i % 2 == 0) {
                dataEvent.add(i);
            } else {
                dataOdd.add(i);
            }
        }
    }
    
    @Override
    public List<Integer> fetchData(ShardingContext shardingContext) {
        int item = shardingContext.getShardingItem();
        List<Integer> subList = null;
        //判断如果是0号分片，从偶数集合中每次抓取100个数据
        if (item == 0) {
            if (dataEvent.size() >= 100) {
                subList = dataEvent.subList(0, 100);
            } else {
                subList = dataEvent.subList(0, dataEvent.size());
            }
            //判断如果是1号分片，从奇数集合中每次抓取100个数据
        } else if (item == 1) {
            if (dataOdd.size() >= 100) {
                subList = dataOdd.subList(0, 100);
            } else {
                subList = dataOdd.subList(0, dataOdd.size());
            }
        }
        return subList;
    }
    
    @Override
    public void processData(ShardingContext shardingContext, List<Integer> list) {
        int item = shardingContext.getShardingItem();
        log.info(item + "号分片，处理的数据" + list);
        if (item == 0) {
            dataEvent.removeAll(list);
        } else if (item == 1) {
            dataOdd.removeAll(list);
        }
    }
}
